package com.xing.binbackend.redis.jedispool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xing.binbackend.redis.RedisStrategy;
import redis.clients.jedis.JedisPooled;

import java.util.Map;

public class JedisPoolStrategy<V> implements RedisStrategy<V> {
    private final JedisPooled jedisPooled;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public JedisPoolStrategy(String host, int port) {
        this.jedisPooled = new JedisPooled(host, port);
    }

    @Override
    public void set(String key, V value) {
        set(key, value, 0); // 默认不过期
    }

    @Override
    public void set(String key, V value, long expireSeconds) {
        try {
            String json = objectMapper.writeValueAsString(value);
            jedisPooled.setex(key, expireSeconds, json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化对象失败", e);
        }
    }

    @Override
    public void multiSet(Map<String, V> keyValueMap) {
        for (Map.Entry<String, V> entry : keyValueMap.entrySet()) {
            set(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public V get(String key, Class<V> clazz) {
        String json = jedisPooled.get(key);
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("反序列化对象失败", e);
        }
    }


    public void close() {
        jedisPooled.close();
    }
}
